"""
Case Type   : 共享存储-工具-系统内部工具-pg_resetxlog
Case Name   : 共享存储模式下，指定-l参数,执行pg_resetxlog命令,
              为新的事务日志指定最小的WAL起始位置，重置日志是否成功
Create At   : 2023/4/25
Owner       : opentestcase019
Description :
    1.查看数据库状态，若为开启状态则关闭数据库;
    2.在对应目录下查看原有xlog列表;
    3.指定-l参数执行pg_resetxlog命令(不需要进入到pg_xlog目录，
      且设置的日志名称必须在已有的之后，例如原本只有1，2，3 -l后面设置6);
    4.再次查看原有xlog列表，是否重置成功（1，2，3 更新后直接为6;
    5.启动数据库;
Expect      :
    1.成功
    2.查看xlog列表成功
    3.执行成功，提示信息为：Transaction log reset
    4.日志重置成功
    5.启动成功
History     :
"""
import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant


class ShareStorageTool(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.primary_node = Node('PrimaryDbUser')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.common = Common()
        self.constant = Constant()
        self.node_num = self.primary_sh.get_node_num()

    def test_sharestorage_tool(self):
        step1 = "-----step1:查看数据库状态，若为开启状态则关闭数据库;expect:成功-----"
        self.logger.info(step1)
        for i in range(self.node_num, 0, -1):
            stop_msg = self.primary_sh.exec_cm_ctl(
                mode='stop', param=f'-n {i} -D {macro.DB_INSTANCE_PATH}')
            self.logger.info(stop_msg)
            self.assertIn(self.constant.cm_stop_instance_success_msg,
                          stop_msg, '执行失败' + step1)
        status = self.primary_sh.exec_cm_ctl(mode='query', param='-Civdp')
        self.logger.info(status)
        self.assertEquals(self.node_num, status.count("Manually stopped"),
                          "执行失败" + step1)

        step2 = "-----step2:在对应目录下查看原有xlog列表;expect:查看xlog列表成功-----"
        self.logger.info(step2)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
            f"dsscmd ls -p +data/pg_xlog0/ -U {macro.UDS_PATH}"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.primary_node, execute_cmd)
        pg_xlog_name = execute_msg.splitlines()[-2].split()[-1].strip()
        pg_xlog_name_new = '0'*(24-len(hex(int(pg_xlog_name, 16)+3))+2)+\
                           hex(int(pg_xlog_name, 16)+3)[2:]

        step3 = "-----step3:指定-l参数执行pg_resetxlog命令(不需要进入到pg_xlog目录，" \
                "且设置的日志名称必须在已有的之后，例如原本只有1，2，3 -l后面设置6);  " \
                "expect:执行成功，提示信息为：Transaction log reset-----"
        self.logger.info(step3)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
            f"pg_resetxlog {macro.DB_INSTANCE_PATH} " \
            f"-l {pg_xlog_name_new.upper()} " \
            f"--enable-dss --socketpath={macro.UDS_PATH} --vgname=+data"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.primary_node, execute_cmd)
        self.assertIn('Transaction log reset', execute_msg, "执行失败" + step3)

        step4 = "-----step4:再次查看原有xlog列表，是否重置成功" \
                "（1，2，3 更新后直接为6）;expect:日志重置成功 -----"
        self.logger.info(step4)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
            f"dsscmd ls -p +data/pg_xlog0/ -U {macro.UDS_PATH}"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.primary_node, execute_cmd)
        self.assertNotIn(pg_xlog_name, execute_msg, "执行失败" + step4)

    def tearDown(self):
        step5 = "-----step5:启动数据库;expect:启动成功-----"
        self.logger.info(step5)
        for i in range(1, self.node_num + 1):
            start_msg = self.primary_sh.exec_cm_ctl(
                mode='start', param=f'-n {i} -D {macro.DB_INSTANCE_PATH}')
            self.logger.info(start_msg)
            self.assertIn(self.constant.cm_start_instance_success_msg,
                          start_msg, '执行失败' + step5)
        time.sleep(30)
        status = self.primary_sh.exec_cm_ctl(mode='query', param='-Civdp')
        self.logger.info(status)
        self.assertIn("cluster_state   : Normal", status, "执行失败" + step5)
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
